package com.thx.common.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;

/**
 * Bean 工厂.
 */
public class BeanFactory {
  private static ApplicationContext ctx = null;

  /**
   * 加载上下文.
   */
  public static void load() {
    if (ctx == null) {

      ServletRequestAttributes ra =
          (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
      WebApplicationContext webAppContext = null;

      if (ra != null) {
        ServletContext sc = ra.getRequest().getServletContext();
        webAppContext = WebApplicationContextUtils.getWebApplicationContext(sc);
      }

      if (webAppContext == null) {
        String[] files;
        files = new String[] {"classpath*:applicationContext.xml"};
        ctx = new FileSystemXmlApplicationContext(files);
      } else {
        ctx = webAppContext;
      }
    }
  }

  public static Object getBean(String objName) {
    return getCtx().getBean(objName);
  }

  public static <T> Object getBean(Class<T> type) {
    return getCtx().getBean(type);
  }

  private static ApplicationContext getCtx() {

    // 如果未加载先加载一下 Spring 环境
    if (ctx == null) {
      load();
    }
    return ctx;
  }
}
